﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace CoD4_Helper.Utils
{
    /// <summary>
    /// Used to get and set Application Settings stored in the XML file
    /// </summary>
    static class SettingsManager
    {
        private static string _settingsFilePath;
        private static string _assemblyDir;
        private static XDocument _xDoc;

        public static bool HasCustomInstDir { get; private set; }
        public static bool HasCustomProfDir { get; private set; }

        public static void Inizialize()
        {
            // Get the assemby directory
            _assemblyDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Remove(0, 6);

            // Get the path to the Settings File(XML)
            _settingsFilePath = Path.Combine(
                _assemblyDir,
                "Settings",
                "AppSettings.xml"
                );

            if (File.Exists(_settingsFilePath))
            {
                // Load the XML
                _xDoc = XDocument.Load(_settingsFilePath);
                // Get Settings->Direcotories->Dir Elements
                var dirs = _xDoc.Root.Element("Directories").Elements("Dir");

                foreach (var item in dirs)
                {
                    switch (item.Attribute("Name").Value)
                    {
                        case "UserInstallationDir":
                            HasCustomInstDir = item.Value != "default" ? true : false;
                            break;
                        case "UserProfilesDir":
                            HasCustomProfDir = item.Value != "default" ? true : false;
                            break;
                    }
                }
            }
            else
            {
                CreateNewSettingsFile();
            }
        }

        /// <summary>
        /// Writes the installation directory to the XML settings file
        /// </summary>
        public static void SetCustomInstDir(string instDir)
        {
            // Get Settings->Direcotories->Dir Elements
            var dirs = _xDoc.Root.Element("Directories").Elements("Dir");
            // Change the directory
            var x =  dirs.Where(p => p.Attribute("Name").Value == "UserInstallationDir").First();
            x.Value = instDir;
            // Save the XML
            _xDoc.Save(_settingsFilePath);

            if (instDir != Utils.COD.GetDefaultInstDir())
                HasCustomInstDir = true;
            
        }

        /// <summary>
        /// Writes the profiles directory to the XML settings file
        /// </summary>
        public static void SetCustomProfDir(string profDir)
        {
            // Get Settings->Direcotories->Dir Elements
            var dirs = _xDoc.Root.Element("Directories").Elements("Dir");
            // Change the directory
            var x = dirs.Where(p => p.Attribute("Name").Value == "UserProfilesDir").First();
            x.Value = profDir;
            // Save the XML
            _xDoc.Save(_settingsFilePath);

            if (profDir != Utils.COD.GetDefaultProfDir())
                HasCustomProfDir = true; 
        }

        /// <summary>
        /// Retrieve the installation directory in the XML settings file
        /// </summary>
        public static string GetCustomInstDir()
        {
            // Get Settings->Direcotories->Dir Elements
            var dirs = _xDoc.Root.Element("Directories").Elements("Dir");
            // Change the directory
            var x = dirs.Where(p => p.Attribute("Name").Value == "UserInstallationDir").First();

            return x.Value;
        }

        /// <summary>
        /// Retrieve the profiles directory in the XML settings file
        /// </summary>
        public static string GetCustomProfDir()
        {
            // Get Settings->Direcotories->Dir Elements
            var dirs = _xDoc.Root.Element("Directories").Elements("Dir");
            // Change the directory
            var x = dirs.Where(p => p.Attribute("Name").Value == "UserProfilesDir").First();

            return x.Value;
        }

        /// <summary>
        /// Creates a new AppSettings XML file with default parameters
        /// </summary>
        private static void CreateNewSettingsFile()
        {
            if (!Directory.Exists(Path.Combine(_assemblyDir, "Settings")))
                Directory.CreateDirectory(_assemblyDir + @"\Settings");

            XmlDocument newDoc = new XmlDocument();
            // Header of the XML: <?xml version="1.0" encoding="utf-8" ?>
            XmlDeclaration xDecl = newDoc.CreateXmlDeclaration("1.0", System.Text.Encoding.UTF8.WebName, null);
            newDoc.AppendChild(xDecl);

            // Add root node
            XmlNode xRoot = newDoc.CreateElement("", "Settings", "");
            newDoc.AppendChild(xRoot);

            // Add Directories node
            XmlNode xSettings = newDoc.CreateElement("Directories");
            xRoot.AppendChild(xSettings);

            XmlAttribute attr1 = newDoc.CreateAttribute("Name");
            attr1.Value = "UserInstallationDir";

            // UID = UserInstallationDir
            XmlElement xElemUID = newDoc.CreateElement("Dir");
            xElemUID.InnerText = "default";
            xElemUID.Attributes.Append(attr1);
            xSettings.AppendChild(xElemUID);

            XmlAttribute attr2 = newDoc.CreateAttribute("Name");
            attr2.Value = "UserProfilesDir";

            // UPD = UserProfilesDir
            XmlElement xElemUPD = newDoc.CreateElement("Dir");
            xElemUPD.InnerText = "default";
            xElemUPD.Attributes.Append(attr2);
            xSettings.AppendChild(xElemUPD);

            try
            {
                newDoc.Save(_settingsFilePath);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Could not create the settings file: \n" + ex.Message);
            }
            
        }

        
    }
}
